<template>
	<view>
		<u-tabs :list="tabBars" line-width="120" :scrollable="false" :current="activeTab" @change="changeTab"></u-tabs>
		<view class="content">
			<view class="detail" v-if="showDetail">
				<view v-if="activeTab == 0">
					<defect-content :data="formData" :isNew="isNew" :isEdit="isEdit" :isView="isView" 
						:isApprove="isApprove" :disableData="disableData" :editData="editData"></defect-content>
				</view>
				<view v-if="activeTab == 1">
					<template v-if="isNew || isEdit || editData.includes('app_base')">
						<defect-file :files="attachFiles" :hasdeleted="true" emitkey="file_defect" @modifyName="fileModifyName"></defect-file>
					</template>
					<template v-else>
						<file-list :files="attachFiles"></file-list>
					</template>
				</view>
				<view v-if="activeTab == 2 && formData.isReplace == '1'">
					<material-content :form="formData" :data="materialList" :isView="isView" 
						:editData="editData" @resetData="resetMaterial"></material-content>
				</view>
			</view>
			
			<view>
				<template v-if="isNew || isEdit">
					<view class="button-groups">
						<button type="primary" @click="saveData">{{$t('baseCommon.buttons.save')}}</button>
						<button type="primary" @click="submitData">{{$t('baseCommon.buttons.submit')}}</button>
					</view>
				</template>
				<template v-else>
					<view v-if="isMore">
						<view class="button-more">
							<view class="btn-first">
								<button type="primary" v-for="(button, index) in buttons" :key="index" @click="handleBtn(button)">
									{{ button.name }}
								</button>
							</view>
							<view class="btn-second" @click="showMoreBtns">
								<button type="primary">
									<uni-icons type="more-filled" color="#fff" size="32"></uni-icons>
								</button>
							</view>
						</view>
						<view class="button-tooltip" v-show="showTooltip" @click="hideToolTip">
							<uni-list :border="false">
								<block v-for="(button, index) in moreBtns" :key="index">
									<uni-list-item :title="button.name" :showArrow="false" :show-extra-icon="true"
										:extra-icon="btnIcon[button.key]" :clickable="true" @click="handleBtn(button)"></uni-list-item>
								</block>
							</uni-list>
						</view>
					</view>
					<view :class="buttons.length > 2 ? 'button-groups-more' : 'button-groups'" v-else>
						<button type="primary" v-for="(button, index) in buttons" :key="index" @click="handleBtn(button)">
							{{ button.name }}
						</button>
					</view>
				</template>
			</view>
		</view>
		
		<!-- 审批意见弹出框 -->
		<uni-popup ref="opinion">
			<opinion-content :type="flowBtn.key" @handleFlow="handleFlow"></opinion-content>
		</uni-popup>
		
		<!-- 申请延期弹出框 -->
		<uni-popup ref="delay">
			<delay-content 
				:data="record" 
				:planEndTime="formData.planEndTime" 
				:operationTeamNo="formData.operationTeamNo" 
				@getRecord="getRecord"
				@close="closePopup">
			</delay-content>
		</uni-popup>
		
		<!-- 申请挂起弹出框 -->
		<uni-popup ref="hang">
			<hang-content 
				:data="record"
				:operationTeamNo="formData.operationTeamNo"
				@getRecord="getRecord"
				@close="closePopup">
			</hang-content>
		</uni-popup>
		
		<!-- 转二三类弹出框 -->
		<uni-popup ref="transfer">
			<transfer-content 
				:data="record"
				:levelNo="formData.dfLevelNo"
				:operationTeamNo="formData.operationTeamNo"
				@getRecord="getRecord"
				@close="closePopup">
			</transfer-content>
		</uni-popup>
	</view>
</template>

<script>
	import defectContent from "./components/detail-content.vue"
	import defectFile from "@/components/business/attach-file/attach-file.vue"
	import fileList from "@/components/business/attach-file/file-list-classify.vue"
	import materialContent from "./components/material-content.vue"
	import opinionContent from "@/components/base/opinion-popup.vue"
	import delayContent from "../components/delay-content.vue"
	import hangContent from "../components/hang-content.vue"
	import transferContent from "../components/transfer-content.vue"
	import {
		getDefectInfo, 
		getDefectInfoByNo, 
		addDefect, 
		getNotifierByLevel, 
		updateDefectStatus, 
		addAndOrder, 
		getApproveOperateInfo, 
		addChangeRecord, 
		addChangeApproveRecord
	} from '@/api/business/defect.js'
	import { getFlowKey, getBaseData } from "./utils/constant.js"
	import { startFlowExpand } from '@/api/base/flow.js'
	import { notice, utilities } from '@/utils/common.js'
	import { saveInnerMessage } from '@/api/platform/common.js'
	import { fileModifyName } from '@/api/base/file.js'
	import { getScheduleDate } from '@/api/business/shiftduty.js'
	import { saveTaskInspDfNo } from '@/api/business/inspect.js'
	import { getWorkTicketDetail } from '@/api/business/ticket.js'
	import { getConectInfoApi, getDataMaterialsApi } from '@/api/business/workorder.js'
	import { collarDetailByWoId } from '@/api/business/material/collar.js'
	import ActionMixin from '@/utils/action.js'
	
	export default {
		mixins: [
			ActionMixin
		],
		data() {
			return {
				// 流程变量，每个页面必须定义
				formData: {
					analysisTime: "",
					analysiser: "",
					analysiserId: "",
					assetId: "",
					assetName: "",
					assetNo: "",
					assetTypeId: "",
					attachFile: "",
					companyCode: "",
					createTime: "",
					createUser: "",
					dfCategory: "",
					dfDesp: "",
					dfId: "",
					dfLevelNo: "",
					dfNo: "",
					dfType: "",
					evaluateDesc: "",
					faultReasonDesc: "",
					faultReasonId: "",
					faultSchemeDesc: "",
					faultSchemeId: "",
					faultSymptonDesc: "",
					faultSymptonId: "",
					findTeamName: "",
					findTeamNo: "",
					finddate: "",
					findperson: "",
					findpersonId: "",
					finishTime: "",
					isReplace: 0,
					locaId: "",
					locaNo: "",
					locaName: "",
					manageObjName: "",
					manageObjNo: "",
					mtnPerson: "",
					mtnPersonId: "",
					mtnTeamName: "",
					mtnTeamNo: "",
					noticeperson: "",
					noticepersonId: "",
					oldEqTypeId: "",
					oldEqTypeName: "",
					oldStdWoId: "",
					oldStdWoName: "",
					oldFaultCode: "",
					oldFaultDescription: "",
					oldReasonAnalysis: "",
					oldTreatmentMeasure: "",
					operationTeamNo: "",
					operationTeamName: "",
					phenomenonId: "",
					phenomenonName: "",
					planEndTime: "",
					remark: "",
					skillNo: "",
					state: "",
					turnFinishTime: "",
					turnLevel: "",
					updateTime: "",
					updateUser: "",
					validateTime: "",
					validateUserId: "",
					validateUserName: "",
					woId: null,
					changeList: []
				},
				// 默认数据
				defaultData: {
					userId: '',
					userName: '',
					date: '',
					dateTime: ''
				},
				// 不展示字段
				disableData: [],
				// 可编辑字段
				editData: [],
				// 初始赋值字段
				initData: [],
				// 校验字段
				requireData: [],
				// 必须字段end
				
				tabBars: [
					{ name: this.$t('baseCommon.other.baseInfo'), id: '0' },
					{ name: this.$t('baseCommon.other.attachInfo'), id: '1' }
				],
				activeTab: 0,
				showDetail: false,
				dfId: '',
				dfNo: '',
				listIndex: 0,
				source: '',
				sourceId: '',
				sourceData: {},
				sourceType: '',
				attachFiles: [],
				showTooltip: false,
				btnIcon: {
					delay: {
						color: '#000000',
						size: '20',
						type: 'paperplane'
					},
					hang: {
						color: '#000000',
						size: '20',
						type: 'locked'
					},
					transfer: {
						color: '#000000',
						size: '20',
						type: 'loop'
					},
					delegate: {
						color: '#000000',
						size: '20',
						type: 'redo'
					}
				},
				ticketTypes: [],
				connectInfoList: [],
				workTicketList: [],
				materialList: [],
				message: {
					canreply: 0,
					content: "",
					createBy: uni.getStorageSync("userId"),
					createTime: "",
					dataStatus: "1",
					dbType: "",
					durationTime: "",
					fileMsg: "",
					groupId: "",
					groupName: "",
					isPublic: 0,
					messageType: "system",
					name: "缺陷",
					ownerId: uni.getStorageSync("userId"),
					ownerName: uni.getStorageSync("userName"),
					receiver: " ",
					receiverId: "",
					receiverTime: "",
					subject: "设备缺陷管理审批抄送",
					updateBy: uni.getStorageSync("userId"),
					updateTime: ""
				},
				record: {
					applyTime: utilities.getNowDateTime(),
					applyedMeasure: "",
					applyer: uni.getStorageSync("userId"),
					applyerName: uni.getStorageSync("userName"),
					changeDesp: "",
					changeTime: "",
					changeType: "",
					dfId: "",
					risk: "",
					toLevel: "",
					toTeamName: "",
					toTeamNo: ""
				},
				approve: {
					approveTime: utilities.getNowDateTime(),
					approver: uni.getStorageSync("userId"),
					approverName: uni.getStorageSync("userName"),
					changeType: "",
					dfId: "",
					isApproved: 0,
					opinion: "通过"
				},
				isNew: false,
				isEdit: false,
				isView: false,
				isApprove: false
			}
		},
		components:{
			defectContent,
			defectFile,
			fileList,
			materialContent,
			opinionContent,
			delayContent,
			hangContent,
			transferContent
		},
		watch: {
			"formData.isReplace"(n, o){
				if(this.formData.isReplace == '1') {
					this.tabBars.push({
						name: this.$t('defect.other.sparePartsInfo'), 
						id: '2'
					})
				} else {
					this.tabBars.forEach(function(tab, index, arr){
						if(tab.id == '2') {
							arr.splice(index, 1)
						}
					})
				}
				this.$forceUpdate()
			},
		},
		onLoad(option) {
			// 初始化操作类型
			this.isNew = option.type === "add"
			this.isEdit = option.type === "edit"
			this.isView = option.type === "view"
			this.isApprove = option.type === "approve"
			
			this.dfId = option.dfId ? option.dfId : ""
			this.dfNo = option.dfNo ? option.dfNo : "" // 主要用于巡检查看缺陷
			this.sourceType = option.sourceType ? option.sourceType : ""
			
			if(option.source){
				this.source = option.source //数据来源
				this.sourceId = option.sourceId //数据来源id
				this.sourceData = JSON.parse(option.sourceData)
			}
			
			if(this.isNew || this.isEdit) {
				this.listIndex = 1
			}
			
			this.init()
			
			// 业务操作日志
			let operateType, operateKey;
			if(this.isNew) {
				operateType = 'add'
				operateKey = ''
			} else if(this.isEdit) {
				operateType = 'edit'
				operateKey = this.dfId
			} else {
				operateType = 'detail'
				operateKey = this.dfId
			}
			this.$saveOpLog(operateType, 'df_mgt', operateKey)
		},
		onShow() {
			uni.$on('file_defect_add', (data)=>{
				if(!this.attachFiles.find(r=>r.id === data.id)) {
					this.attachFiles.push(data)
				}
			})
			uni.$on('file_defect_del', (data)=>{
				this.attachFiles.find(function(r, index, arr){
					if(r.id == data.id){
						arr.splice(index, 1)
					}
				})
			})
		},
		onUnload() {
			uni.$off('file_defect_add')
			uni.$off('file_defect_del')
		},
		methods: {
			async init() {
				// 初始化默认数据
				this.loadDefaultData()
				
				// 创建的话,需要初始化数据
				if (this.isNew) {
					this.formData.state = 'draft'
					this.formData.dfType = '1'
					this.formData.createTime = this.defaultData.dateTime
					this.formData.createUser = this.defaultData.userId
					this.formData.finddate = this.defaultData.dateTime
					this.formData.findperson = this.defaultData.userName
					this.formData.findpersonId = this.defaultData.userId
					this.formData.findTeamNo = uni.getStorageSync("userOrgId")
					this.formData.findTeamName = uni.getStorageSync("userOrgName")
					this.formData.companyCode = uni.getStorageSync("companyId")
					this.formData.companyName = uni.getStorageSync("companyName")
					
					switch (this.source) {
						case 'xundianjian': //巡点检
							this.formData.locaId = this.sourceData.locaId //设备位置id
							this.formData.locaNo = this.sourceData.locaNo //设备位置no
							this.formData.locaName = this.sourceData.locaName //设备位置名称
							this.formData.operationTeamNo = this.sourceData.companyCode //场站
							this.formData.attachFile = this.sourceData.attachFile;
							this.formData.dfDesp = this.sourceData.dfDesp || '' //缺陷描述
							break;
						case 'woFault': //风机故障登记缺陷
							this.formData.locaId = this.sourceData.locaId //设备位置id
							this.formData.locaNo = this.sourceData.locaNo //设备位置no
							this.formData.locaName = this.sourceData.locaName //设备位置名称	
							this.formData.dfType = this.sourceData.dfType
							this.formData.dfDesp = this.sourceData.dfDesp || '' //缺陷描述
							this.formData.dfLevelNo = this.sourceData.dfLevelNo || '' //缺陷等级
							this.formData.phenomenonId = this.sourceData.phenomenonId || '' //缺陷现象
							this.formData.operationTeamNo = this.sourceData.companyCode || '' //场站
							break;
						case 'sisAlarm': //sis告警信息登记缺陷
							this.formData.locaId = this.sourceData.locaId //设备位置id
							this.formData.locaNo = this.sourceData.locaNo //设备位置no
							this.formData.locaName = this.sourceData.locaName //设备位置名称
							this.formData.dfDesp = this.sourceData.alarmDesc || '' //缺陷描述
							break;
					}
				} else {
					// 缺陷基本信息
					if(this.dfNo) {
						await getDefectInfoByNo(this.dfNo).then(res=>{
							this.dfId = res.data.dfId
							this.formData = res.data
							
							if(res.data.attachFile){
								this.attachFiles = JSON.parse(res.data.attachFile)
							}
						})
					} else {
						await getDefectInfo(this.dfId).then(res=>{
							this.formData = res.data
							
							if(res.data.attachFile){
								this.attachFiles = JSON.parse(res.data.attachFile)
							}
						})
					}
					// 缺陷变更信息
					await getApproveOperateInfo(this.dfId, '').then(res=>{
						this.formData.changeList = res.data.changeList
					})
					
					if(this.formData.woId) {
						// 缺陷物资信息
						getDataMaterialsApi({ woId: this.formData.woId }).then(res=>{
							this.materialList = res.data
							
							collarDetailByWoId(this.formData.woId).then(res=>{
								if(res.data) {
									res.data.forEach(collar => {
										this.materialList.forEach(material => {
											if(collar.collarItemId === material.collarItemId) {
												material.collectionQty = collar.quantity
												material.actualQty = collar.returnedQuantity == null ? null : collar.quantity - collar.returnedQuantity
												material.actualAmt = collar.returnedQuantity == null ? null : ((collar.quantity - collar.returnedQuantity) * material.unitCost).toFixed(2)
											}
										})
									})
								}
							})
						})
						// 缺陷关联信息
						this.getconnectInfoList()
					}
				}
				
				// 流程初始字段设置
				if(!this.isView) {
					let baseData = getBaseData()
					this.disableData = baseData.disableData
					this.editData = baseData.editData
				}
				
				// 流程信息
				if(this.isApprove) {
					await this.getFlowTaskInfo(this.dfId)
					// 初始化数据
					this.loadInitData()
				}
				
				// 页面标题
				uni.setNavigationBarTitle({
				　　title: this.isView ? this.$t('common.buttons.see') : (this.isNew || this.isEdit) ? this.$t('defect.state.defReg') : this.nodeName
				})
				
				this.showDetail = true
			},
			// 获取缺陷关联信息
			getconnectInfoList() {
				getConectInfoApi({ woId: this.formData.woId }).then(res=>{
					res.data.forEach(item=>{
						// 关联信息过滤工作票、领料单、退料单
						if(item.boTypeNo == 'wt_wt' || item.boTypeNo == 'ex_mat_use' || item.boTypeNo == 'ex_mat_gb') {
							item.value = item.boNo + "-" + item.boContent
							this.connectInfoList.push(item)
						}
						// 主要用于申请验收时校验工作票是否完结
						if(item.boTypeNo == 'wt_wt') {
							getWorkTicketDetail(item.boId).then(res=>{
								this.workTicketList.push(res.data)
							})
						}
					})
				})
			},
			changeTab(e) {
				this.activeTab = e.index
			},
			saveData() {
				if(!this.validateForm()){
					return;
				}
				
				this.formData.attachFile = JSON.stringify(this.attachFiles)
				addDefect(this.formData).then(res=>{
					this.formData.dfId = res.data.dfId
					if(res.code === 0) {
						uni.showToast({
							title: this.$t('defect.message.defectRegisterSuccess'),
							duration: 500
						});
						
						if(null !== this.sourceId && '' !== this.sourceId) {
							this.saveSourceData(res.data.dfId)
						}
						
						if(this.source) {
							const eventChannel = this.getOpenerEventChannel();
							eventChannel.emit('eventData', '');
							uni.navigateBack()
						} else {
							utilities.back(this.sourceType, this.listIndex)
						}
					}
				})
			},
			submitData() {
				const _this = this
				if(!_this.validateForm()){
					return;
				}
				uni.showModal({
					title: _this.$t('baseCommon.message.tips'),
					content: _this.$t('defect.message.sureStartProcess'),
					success: function (res) {
						if (res.confirm) {
							// 保存数据
							_this.formData.attachFile = JSON.stringify(_this.attachFiles)
							addDefect(_this.formData).then(res=>{
								if(!_this.dfId){
									_this.dfId = _this.formData.dfId = res.data.dfId
								}
								
								if(null !== _this.sourceId && '' !== _this.sourceId) {
									_this.saveSourceData()
								}
								
								_this.startFlow()
							})
						}
					}
				})
			},
			async startFlow() {
				let flowkey = getFlowKey()
				let approveRequest = {
					defKey: flowkey.defKey,
					formKey: flowkey.formKey,
					ids: this.dfId,
					nodeUsers: ''
				}
				if (this.source === 'woFault') { // 是风机故障过来得登记，，DEFECT_SELECT：2 消缺 3 鉴定策划
					if (this.formData.dfLevelNo === '1') { // 一类跳转鉴定策划
						approveRequest.flowParam = encodeURI(encodeURI('{"DEFECT_SELECT":"3"}'))
						approveRequest.state = 'confirming'// 鉴定策划
					} else {
						approveRequest.flowParam = encodeURI(encodeURI('{"DEFECT_SELECT":"2","XQ_FZR":"' + this.formData.mtnPersonId + '"}'))// 消缺负责人
						approveRequest.state = 'processing'// 消缺
					}
				} else {
					let param = { deptAlia: 'HJX_JK', isNo: this.formData.dfLevelNo } // deptId:集控中心  isNo 1 当值值长  空当值所有人员
					approveRequest.flowParam = encodeURI(encodeURI('{"DEFECT_SELECT":"1"}'))// DEFECT_SELECT：1 运行确认
					approveRequest.state = 'confirming'// 运行确认
					await getScheduleDate(param).then(res=>{
						if(res.data == null || res.data.length == 0){
							notice.toast(this.$t('defect.message.notStartFlowWithNoPeople'))
							return;
						}else{
							const executors = []
							res.data.forEach(item=>{
								executors.push({
									id: item.id,
									name: item.name,
									type: "employee",
									groupType: ""
								})
							})
							const data = []
							data.push({
								nodeId: 'Activity_13gd96i',
								executors: executors
							})
							approveRequest.nodeUsers = JSON.stringify(data)
						}
					})
				}
				
				// 发起流程
				startFlowExpand(approveRequest).then(res=>{
					if(res.state === 200) {
						// 更新状态
						updateDefectStatus(this.dfId, approveRequest.state).then(res=>{
							if(res.code === 0) {
								uni.showToast({
									title: this.$t('defect.message.processStartedSuccess'),
									duration: 500
								});
								if(this.source) {
									const eventChannel = this.getOpenerEventChannel();
									eventChannel.emit('eventData', '');
									uni.navigateBack()
								} else {
									utilities.back(this.sourceType, this.listIndex)
								}
							}
						})
					}
				})
			},
			handleBtn(button) {
				this.flowBtn = button
				
				// 表单校验
				if(this.validateFlow()) {
					// 消缺-申请验收
					if(this.flowBtn.key == 'accept') {
						// 校验工作票是否完结
						if(this.validateTicket()) {
							this.applyAccept()
						}
					}
					// 消缺-申请延期
					else if(this.flowBtn.key == 'delay') {
						this.applyDelay()
					}
					// 消缺-申请挂起
					else if(this.flowBtn.key == 'hang') {
						this.applyHang()
					}
					// 消缺-转二三类
					else if(this.flowBtn.key == 'transfer') {
						this.applyTransfer()
					}
					// 消缺-转办
					else if(this.flowBtn.key == 'delegate') {
						this.applyDelegate()
					}
					else {
						// 审批意见
						this.$refs.opinion.open()
					}
				}
			},
			handleFlow(opinion) {
				this.$refs.opinion.close()
				this.opinion = opinion
				
				this.emitButtonEventHandler(this.flowBtn.key)
			},
			// 保存表单
			saveForm(type) {
				if(!this.validateForm()){
					return;
				}
				
				this.formData.attachFile = JSON.stringify(this.attachFiles)
				
				if(type === 'add') {
					addDefect(this.formData)
				} else if(type === 'addAndOrder') {
					addAndOrder(this.formData)
				} else {
					addDefect(this.formData)
				}
			},
			// 更新状态
			updateState() {
				addDefect(this.formData)
			},
			// 更新表单
			async updteForm(targetField) {
				if(targetField == 'dfLevelNo') {
					await getNotifierByLevel(this.formData[fromField]).then(res=>{
						let timeLimit = res.data.split("--")[2]
						this.formData.planEndTime = utilities.getCalDateTime(this.formData.finddate, timeLimit)
					})
				}
				addDefect(this.formData)
			},
			validateForm() {
				var formFlag = true
				if(!this.formData.operationTeamNo){
					notice.toast(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('common.field.deptAlias') }))
					formFlag = false
				}
				if(!this.formData.locaName){
					notice.toast(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('defect.common.locaName') }))
					formFlag = false
				}
				if(!this.formData.dfLevelNo){
					notice.toast(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('defect.common.defectLev') }))
					formFlag = false
				}
				if(!this.formData.dfType){
					notice.toast(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('defect.defInfo.dfType') }))
					formFlag = false
				}
				if(this.formData.dfType == '2' && !this.formData.dfCategory){
					notice.toast(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('defect.defInfo.dfCategory') }))
					formFlag = false
				}
				if(!this.formData.dfDesp){
					notice.toast(this.$t('baseCommon.message.pleaseEnter', { title: this.$t('defect.common.defectCom') }))
					formFlag = false
				}
				if(!this.formData.findperson){
					notice.toast(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('defect.defInfo.findperson') }))
					formFlag = false
				}
				if(!this.formData.mtnPerson) {
					notice.toast(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('defect.defInfo.xqMtnPerson') }))
					formFlag = false
				}
				return formFlag
			},
			validateFlow() {
				var formFlag = true
				let that = this
				for (const [key, rules] of Object.entries(that.requireData)) {
					// 特殊处理，移动端消缺节点检修交代不在此处校验
					if(key == 'maintenanceExplain') {
						continue
					}
					
					// 必输校验
					if(rules.required && that.formData.hasOwnProperty(key) && !that.formData[key]) {
						notice.toast(rules.message)
						formFlag = false
						break
					}
					// TODO 其他校验待页面重构完成后补充
				}
				return formFlag
			},
			validateTicket() {
				var formFlag = true
				let someNotFinished = this.workTicketList.some(link =>
					!["end", "qualified", "unqualified", "abolished", ].includes(link.state))
				if (someNotFinished) {
					notice.toast(this.$t('defect.message.unfinishedWorkTicket'))
					formFlag = false
				}
				return formFlag
			},
			// 申请验收
			applyAccept() {
				let that = this
				uni.navigateTo({
					url: '/pages/business/defect/wind/apply-accept?form=' + JSON.stringify(that.formData),
					events: {
						handleCheck(data) {
							that.getRecord(data)
							Object.assign(that.formData, data)
							that.emitButtonEventHandler("agree")
						}
					}
				})
			},
			// 申请延期
			applyDelay() {
				this.showTooltip = false
				this.$refs.delay.open()
			},
			// 申请挂起
			applyHang() {
				this.showTooltip = false
				this.$refs.hang.open()
			},
			// 转二三类
			applyTransfer() {
				this.showTooltip = false
				this.$refs.transfer.open()
			},
			// 转办
			applyDelegate() {
				this.showTooltip = false
				uni.navigateTo({
					url: '/pages/base/flow/delegate?type=defect&taskId=' + this.taskId + '&bizKey=' + this.dfId
				})
			},
			showMoreBtns() {
				this.showTooltip = true
			},
			hideToolTip() {
				this.showTooltip = false
			},
			addChangeRecord() {
				this.record.changeType = this.variableMap.DEFECT_SELECT
				addChangeRecord(this.record)
			},
			addChangeApproveRecord(type, isAgree) {
				this.approve.dfId = this.dfId
				this.approve.isApproved = isAgree ? 0 : 1
				this.approve.opinion = this.opinion
				this.approve.changeType = type
				addChangeApproveRecord(this.approve)
			},
			closePopup(type, data) {
				this.$refs[`${type}`].close()
				
				let params = {
					users: data,
					isSelect: "N",
					isSubFlow: true
				}
				if(type == "delay"){
					this.formData.turnFinishTime = this.record.changeTime
				}
				if(type == "transfer"){
					this.formData.turnLevel = this.record.toLevel
				}
				
				this.applyCheck(params)
			},
			applyCheck(data) {
				let executors = []
				data.users.forEach(user=>{
					executors.push(user)
				})
				this.flowParams.nodeUsers = []
				this.flowParams.nodeUsers.push({
					executors: executors
				})
				
				this.opinion = this.$t('common.buttons.agree')
				this.emitButtonEventHandler("agree")
			},
			sendMessage() {
				let userid = uni.getStorageSync("userId")
				let username = uni.getStorageSync("userName")
				let datetime = utilities.getNowDateTime()
				let status = this.formData.dfLevelNo == "1" ? this.$t('defect.state.appPlan') : this.$t('defect.state.DefElimination')
				
				this.message.receiver = this.formData.noticeperson
				this.message.receiverId = this.formData.noticepersonId
				this.message.receiverTime = datetime
				this.message.createTime = datetime
				this.message.updateTime = datetime
				this.message.content = "设备缺陷管理审批抄送，"+username+"在"+datetime+"发起的设备缺陷流程<a href=javascript:link >"+this.formData.dfNo+"</a>(缺陷描述："+this.formData.dfDesp+")已到<"+status+">状态"
				saveInnerMessage(this.message)
				
				utilities.back(this.sourceType, this.listIndex)
			},
			getRecord(data) {
				this.record.dfId = this.dfId
				Object.assign(this.record, data)
			},
			saveSourceData(dfId) {
				// 巡检表dfNo字段改为存缺陷表dfId字段
				if('xundianjian' === this.source) { //巡点检
					let data = {
						taskInspId: this.sourceId,
						dfNo: dfId,
						isAbnormalHandled: 1,
						handlingMemo: this.$t('defect.message.transferredDefect')
					}
					saveTaskInspDfNo(data) //更新巡点检
				}
				// getDefectInfo(dfId).then(res=>{
				// 	if('xundianjian' === this.source) { //巡点检
				// 		let data = {
				// 			taskInspId: this.sourceId,
				// 			dfNo: res.data.dfNo,
				// 			handlingMemo: "已转消缺"
				// 		}
				// 		saveTaskInspDfNo(data) //更新巡点检
				// 	}
				// })
			},
			resetMaterial(data) {
				this.materialList = JSON.parse(JSON.stringify(data));
			},
			// 文件重命名
			fileModifyName(data) {
				let params = {
					attachmentId: data.file.id,
					fileName: data.newFileName
				}
				fileModifyName(params).then(res=>{
					if(res.state === 200) {
						data.file.name = data.newFileName
						this.attachFiles.forEach(function(value, index, arr){
							if(data.file.id === value.id) {
								arr.splice(index, 1, data.file)
							}
						})
						
						this.formData.attachFile = JSON.stringify(this.attachFiles)
						addDefect(this.formData)
					}
				})
			}
		},
		onNavigationBarButtonTap() {
			if (this.isNew || this.isEdit || this.formData.state == 'draft') {
				notice.toast(this.$t('defect.message.processHasNotStarted'))
				return false
			}
			uni.navigateTo({
				url: '/pages/base/flow/flow-history?bizKey=' + this.formData.dfId + "&defKey=" + this.procDefKey
			})
		},
		onBackPress() {
			setTimeout(()=>{
				utilities.backQuick(this.sourceType == 'offline' ? this.sourceType : 'back')
			}, 10);
		}
	}
</script>

<style lang="scss">
	@import '@/static/style/common-detail.scss';
</style>
<style lang="scss" scoped>
	.detail {
		padding-top: 8px;
	}
	
	/deep/ .uni-list-item__content-title {
		text-align: center;
	}
	
	/deep/ .fileinfo {
		padding-top: 12px;
	}
</style>
